#define _CRT_SECURE_NO_WARNINGS 1
#include "Sort.h"

void InsertSort(int* data, int sz)
{
	assert(data);
	for (int i = 1; i < sz; i++)
	{
		{
			int tmp = data[i];
			int end = i-1;

			while (end >= 0)
			{
				if (tmp < data[end])
				{
					data[end + 1] = data[end];
					end--;
				}
				else
				{
					break;
				}
			}

			data[end + 1] = tmp;
		}
	}
}

void PrintArray(int* data, int sz)
{
	assert(data);
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", data[i]);
	}
	printf("\n");
}

void ShellSort(int* data, int sz)
{
	int gap = sz;
	while (gap > 1)
	{
		gap /= 2;
		// gap = gap / 3 + 1;
		for (int i = 0; i < sz - gap; i++)
		{
			int end = i;
			int tmp = data[i + gap];
			while (end >= 0)
			{
				if (tmp < data[end])
				{
					data[end + gap] = data[end];
					end -= gap;
				}
				else
				{
					break;
				}
			}

			data[end + gap] = tmp;
		}

		// PrintArray(data, sz);
	}
}

void Swap(int* p1, int* p2)
{
	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void SelectSort(int* data, int sz)
{
	int left = 0, right = sz - 1;
	while (left < right)
	{
		int Mini = left, Maxi = left;
		for (int i = left + 1; i <= right; i++)
		{
			if (data[Mini] > data[i])
			{
				Mini = i;
			}

			if (data[Maxi] < data[i])
			{
				Maxi = i;
			}
		}

		Swap(&data[left], &data[Mini]);

		if (left == Maxi)
		{
			Maxi = Mini;
		}

		Swap(&data[right], &data[Maxi]);

		left++;
		right--;
	}

}

void AdjustDown(int* data, int parent, int sz)
{
	int child = parent * 2 + 1;
	while (child < sz)
	{
		if (child + 1 < sz && data[child+1] > data[child])
		{
			child++;
		}

		if (data[child] > data[parent])
		{
			Swap(&data[child], &data[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapSort(int* data, int sz)
{
	for (int i = (sz - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDown(data, i, sz);
	}

	int end = sz - 1;
	while (end)
	{
		Swap(&data[0], &data[end]);
		AdjustDown(data, 0, end);
		end--;
	}
}

void BubbleSort(int* data, int sz)
{
	for (int j = 0; j < sz - 1; j++)
	{
		bool exchange = false;
		for (int i = 0; i < sz - 1 - j; i++)
		{
			if (data[i] > data[i + 1])
			{
				Swap(&data[i], &data[i + 1]);
				exchange = true;
			}
		}

		if (exchange == false)
		{
			break;
		}
	}

}